///////////////////////////////////////////////////////////////////////////////
//
// Licensed under the MIT License
//
// Copyright (c) 2010 Chris Colinsky
// All Rights Reserved
//
// version	0.5
// http://code.google.com/p/sugarcookie/
// http://code.google.com/p/sugarcookie/wiki/License
//
////////////////////////////////////////////////////////////////////////////////

package sugarcookie.file {
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.collections.IViewCursor;
	import mx.utils.ObjectUtil;
	
	import sugarcookie.collections.EnhancedArrayCollection;
	import sugarcookie.events.GenericEvent;
	import sugarcookie.file.FileLoader;
	
	public class FileQueue extends EventDispatcher {
		public static const LOAD_COMPLETE:String = "onLoadComplete";
		public static const ITEM_LOAD_COMPLETE:String = "onItemLoadComplete";
		
		private var _loaded:EnhancedArrayCollection;
		private var _queue:ArrayCollection;
		private var _cursor:IViewCursor;
		private var _path:String = "";
		
		public function FileQueue() {
			super(this);
			_queue = new ArrayCollection();
			_loaded = new EnhancedArrayCollection();
		}
		
		public function set path(p:String):void {
			_path = p;
		}
		
		public function addToQueue(id:String,uri:String):void {
			_queue.addItem([id,uri]);
		}
		
		public function initQueue():void {
			_cursor = _queue.createCursor();
			doLoad();
		}
		
		public function clearQueue():void {
			_queue.removeAll();
		}
		
		public function clearLoaded():void {
			_loaded.removeAll();
		}
		
		public function clearAll():void {
			clearQueue();
			clearLoaded();
		}
		
		public function getFile(id:String):FileLoader {
			return _loaded.containsKey(id)?FileLoader(_loaded.getItemAtKey(id)):null;
		}
		
		private function doLoad():void {
			var _loader:FileLoader = new FileLoader(_path+_cursor.current[1]);
			_loader.addEventListener(FileLoader.LOAD_COMPLETE,onComplete,false,0,true);
			_loaded.addItemWithKey(_cursor.current[0],_loader);
			_loader.load();
		}
		
		private function onComplete(evt:GenericEvent):void {
			evt.target.removeEventListener(FileLoader.LOAD_COMPLETE,onComplete);
			var loadedId:String = _cursor.current[0];
			dispatchEvent(new GenericEvent(FileQueue.ITEM_LOAD_COMPLETE,true,false,null,true,{id:loadedId}));
			
			if (_cursor.moveNext()) doLoad();
			else dispatchEvent(new GenericEvent(FileQueue.LOAD_COMPLETE,true,false,null,true,{lastId:loadedId}));
		}
	}
}